<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="登录账号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input
        v-model="listQuery.realname"
        placeholder="用户名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.type" style="width: 200px;" class="filter-item">
        <el-option
          v-for="item in userType"
          :key="item.value"
          :label="item.label"
          :value="item.value" />
      </el-select> -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">
        {{ lang.systemManage.user.index.filters.searchBtn }}
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="default"
        icon="el-icon-refresh"
        @click="tableReset()">
        {{ lang.systemManage.user.index.filters.refreshBtn }}
      </el-button>
      <el-button v-permission="'sys-user-add'" v-waves class="filter-item right-btns" type="success" @click="edit()"><svg-icon icon-class="add"/> 新增</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="listQuery.list"
      :stripe="true"
      :border="true"
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column type="index" align="center"/>
      <el-table-column label="登录账号" align="left" min-width="60px">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'用户名称'" align="left" min-width="80px" prop="realname" />
      <el-table-column :label="'单位'" align="left" min-width="80px" >
        <template slot-scope="scope">
          <span class="link-type" @click="editOragn(scope.row)">{{ scope.row.organName || '未设置' }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="lang.systemManage.user.index.tableCol.roleName" min-width="80px">
        <template slot-scope="scope">
          <!-- <el-dropdown trigger="click" placement="bottom" @command="(command) => { roleChange(scope.row, command) }">
            <span :class="{err: !roleNameById(scope.row.roleId).code}" class="link-type link-edit" title="点击修改">
              {{ roleNameById(scope.row.roleId).name }}
              <-!-- <i class="el-icon-arrow-down el-icon--right" /> -- >
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in roles"
                :key="item.id"
                :command="item.id"
                :disabled="item.enable !== 1"
                :title="item.remark">{{ item.roleName }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <!-- <el-select size="mini" style="width: 140px;">
            <el-option label="文字1" value="1" />
            <el-option label="文字2" value="2" />
            <el-option label="文字3" value="3" />
          </el-select> -->
          <!-- <el-button size="mini" type="primary">确认</el-button> -->
          <!-- <el-button size="mini" type="default">取消</el-button> -->
          <span class="link-type" @click="editRole(scope.row)">{{ (scope.row.roleList || []).map(r => r.name).join('，') || '未设置' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="lang.systemManage.user.index.tableCol.createTime" align="center">
        <template slot-scope="{ row }">
          {{ row.createTime | moment('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column> -->
      <el-table-column :label="lang.systemManage.user.index.tableCol.enable" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" :disabled="scope.row.type === -1 || !$hasPermission('sys-user-change-status')" @change="enableSet(scope.row)" />
          <span>（{{ scope.row.enable ? '启用' : '禁用' }}）</span>
        </template>
      </el-table-column>

      <el-table-column v-if="$hasPermission('sys-user-edit,sys-user-reset-password,sys-user-reset-delete')" :label="lang.systemManage.user.index.tableCol.operation.name" align="center" class-name="small-padding fixed-width" width="260px">
        <template slot-scope="scope">
          <!-- <el-button v-waves type="info" plain size="mini" @click="editRole(scope.row)">配置角色</el-button> -->
          <el-button v-permission="'sys-user-edit'" v-waves type="primary" plain size="mini" @click="edit(scope.row)">
            {{ '修改' }}
          </el-button>
          <el-button v-permission="'sys-user-reset-password'" v-waves type="danger" plain size="mini" @click=" repassword(scope.row)">
            {{ lang.systemManage.user.index.tableCol.operation.resetPassword }}
          </el-button>
          <el-button v-permission="'sys-user-reset-delete'" v-waves :disabled="scope.row.type == -1" type="danger" plain size="mini" @click="del(scope.row)">
            {{ lang.systemManage.user.index.tableCol.operation.delete }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="listQuery.total>0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.rows"
      @pagination="getList" />
    <!--配置角色弹窗-->
    <el-dialog
      :visible.sync="roleDialogVisible"
      title="配置角色"
      width="600px">
      <!-- <div v-for="item in roles" :key="item.id" style="margin-top:5px">
        <el-radio v-model="roleSelect" :label="item.id" border>{{ item.roleName }}</el-radio>
      </div> -->
      <div>
        <el-checkbox v-for="item in roles" :key="item.id" v-model="userRoleTemp.ids" :label="item.id" border style="margin-top:5px">{{ item.name }}</el-checkbox>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleSave()">确 定</el-button>
      </span>
    </el-dialog>

    <add-edit-dialog ref="editDialog" :loading="isEditSubmitting" @ok="handleEditOk"/>
    <set-organ-dialog ref="setOrganDialog" :loading="isSetOrganSubmitting" @ok="handleSetOrganOk"/>
  </div>
</template>

<script>
import { getPages, userUpdateDisabled, userDel, updateUserRole, reUserPassword, userAdd, userUpdate, updateUserOrgan } from '@/api/systemManage/user'
import { getAllRole } from '@/api/systemManage/role'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import DelBoxMixin from '@/mixins/delBox'
import { mapGetters } from 'vuex'

import addEditDialog from './add-edit'
import setOrganDialog from './set-organ'

export default {
  name: 'UserManage',
  components: { Pagination, addEditDialog, setOrganDialog },
  directives: { waves },
  mixins: [DelBoxMixin],

  props: {
    options: {
      type: Object,
      default: function() { return {} }
    }
  },

  data() {
    return {
      roleDialogVisible: false,
      userRoleTemp: { ids: null },
      roles: [],
      roleSelect: null,
      listLoading: true,
      listQuery: {},

      isEditSubmitting: false,
      isSetOrganSubmitting: false
    }
  },
  computed: {
    ...mapGetters([
      'lang'
    ]),
    userType() {
      const userType = this.$store.getters.userType
      const _keys = Object.keys(userType)
      const newUserType = [
        { label: this.lang.systemManage.user.index.filters.typePlaceholder, value: '' }
      ]
      for (let i = 0; i < _keys.length; i++) {
        if (_keys[i] === '3') continue
        newUserType.push({
          label: userType[_keys[i]].name,
          value: _keys[i]
        })
      }
      return newUserType
    },
    roleNameById() {
      return (id) => {
        const res = {
          name: '角色配置不正确',
          code: 0
        }
        if (!id) {
          res.name = '请配置角色'
          res.code = 0
          return res
        }
        for (let i = 0; i < this.roles.length; i++) {
          if (this.roles[i].id === id) {
            res.code = 1
            res.name = this.roles[i].roleName
            return res
          }
        }
        return res
      }
    }
  },
  created() {
    this.getRoles()
    this.tableReset()
  },
  methods: {
    tableReset() {
      this.listQuery = {
        page: 1,
        rows: 10,
        total: 0,
        username: null,
        type: '',
        list: null
      }
      this.getList()
    },
    getRoles() {
      // getRoleList({ enable: 1 }).then(response => {
      getAllRole().then(response => {
        this.roles = response.data
      })
    },
    getList() {
      this.listLoading = true
      const params = Object.assign({}, this.listQuery)
      delete params.total
      delete params.list

      params.organId = (this.options || {}).organId

      getPages(params).then(response => {
        this.listQuery.list = response.data.list
        this.listQuery.total = response.data.total
        this.listLoading = false
      }).catch(e => {
        this.listLoading = false
        this.$message.error(e.message)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    edit(item) {
      // const type = item ? 'detail' : 'create'
      // const id = item ? item.id : 0
      // this.$router.push(`/system-manage/user-manage/${type}/${id}`)
      if (item && item.id) {
        this.$refs.editDialog.show({
          id: item ? item.id : 0
        })
      } else {
        this.$refs.editDialog.show()
      }
    },

    handleEditOk(data, isEdit) {
      this.isEditSubmitting = true
      const invoke = isEdit ? userUpdate : userAdd
      if (!isEdit) {
        data.organId = (this.options || {}).organId
      }
      invoke(data).then(resp => {
        this.getList()

        this.$message.success(resp.message)
        this.isEditSubmitting = false
        this.$refs.editDialog.close()
      }).catch(resp => {
        this.$message.error(resp.message)
        this.isEditSubmitting = false
      })
    },

    // 编辑用户角色
    editRole(item) {
      if (!this.$hasPermission('sys-user-set-role')) {
        return
      }
      const userId = item ? item.id : 0
      // getUserRole(userId).then(response => {
      //   this.roleSelect = response.data
      //   this.userRoleTemp = { userId: userId, ids: this.roleSelect }
      //   this.roleDialogVisible = true
      // })
      this.roleSelect = (item.roleList || []).map(r => r.id)
      this.userRoleTemp = { userId: userId, ids: this.roleSelect }
      this.roleDialogVisible = true
    },
    editRoleSave() {
      updateUserRole(this.userRoleTemp).then(response => {
        this.$message.success(response.message)
        this.userRoleTemp = { ids: null }
        this.roleDialogVisible = false
        // this.listQuery.list.findIndex(t => t.id === this.userRoleTemp.userId)
        this.getList()
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },
    del(item) {
      this.$$delBox().then(() => {
        userDel(item.id).then(res => {
          this.$message.success(res.message)
          this.getList()
        }).catch(e => {
          this.$message.error(e.message)
        })
      }).catch(() => {})
    },
    // 重置密码为123456
    repassword(item) {
      this.$confirm('确定重置当前账号密码为123456, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reUserPassword(item.id).then(response => {
          this.$message.success(response.message)
          // this.getList()
        }).catch(response => {
          this.$message.error(response.message)
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消' })
      })
    },
    enableSet(item) {
      // item.$statusDisabled = true
      const enable = item.enable
      userUpdateDisabled(item.id, enable).then(res => {
        // item.$statusDisabled = false
        this.getList()
        this.$message.success(res.message)
        // if (res.code === 200) {
        //   this.$message.success(`已${enable === 1 ? '启用' : '禁用'}`)
        // } else {
        //   this.$message.error(res.message)
        // }
      }).catch(res => {
        // this.$message.error(this.$store.getters.errorMsg)
        // item.$statusDisabled = false
        this.$message.error(res.message)
      })
    },
    roleChange(item, command) {
      const params = {
        userId: item.id,
        ids: command
      }
      updateUserRole(params).then(resp => {
        // if (response.code === 200) {
        //   this.$message.success('修改成功！')
        //   item.roleId = command
        //   this.$forceUpdate()
        // } else {
        //   this.$message.error(response.message)
        // }
        this.$message.success(resp.message)
        item.roleId = command
        this.$forceUpdate()
      }).catch(resp => {
        this.$message.success(resp.message)
      })
    },

    // //////////////////////////////
    // 设置单位
    editOragn(item) {
      if (!this.$hasPermission('sys-user-set-unit')) {
        return
      }
      if (item) {
        this.$refs.setOrganDialog.show({
          userId: item.id,
          username: item.username,
          realname: item.realname,
          organId: item.organId
        })
      }
    },

    handleSetOrganOk(data) {
      if (data) {
        this.isSetOrganSubmitting = true
        updateUserOrgan(data).then(resp => {
          this.isSetOrganSubmitting = false
          this.$refs.setOrganDialog.close()
          this.$message.success(resp.message)
          this.getList()
        }).catch(resp => {
          this.isSetOrganSubmitting = false
          this.$message.error(resp.message)
        })
      }
    }
  }
}
</script>
